<template>
  <div class="health-management-page">
    <van-nav-bar
      title="健康管理"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
      class="custom-nav-bar"
    />

    <div class="feature-intro">
      <div class="intro-content">
        <div class="intro-icon">🏥</div>
        <div class="intro-text">
          <h3>AI健康管理</h3>
          <p>健康数据分析与个性化建议</p>
        </div>
      </div>
    </div>

    <div class="health-container">
      <div class="input-section">
        <h4>📊 健康数据输入</h4>
        <van-field
          v-model="healthData"
          placeholder="例如：今天走了8000步，睡了7小时，吃了三餐..."
          type="textarea"
          rows="4"
          autosize
        />

        <div class="analysis-type">
          <van-radio-group v-model="analysisType">
            <van-radio name="comprehensive">综合分析</van-radio>
            <van-radio name="exercise">运动分析</van-radio>
            <van-radio name="diet">饮食分析</van-radio>
            <van-radio name="sleep">睡眠分析</van-radio>
          </van-radio-group>
        </div>

        <van-button
          type="primary"
          block
          :loading="isLoading"
          @click="analyzeHealth"
          :disabled="!healthData.trim()"
        >
          获取健康建议
        </van-button>
      </div>

      <div class="quick-input">
        <h4>⚡ 快速输入</h4>
        <div class="quick-buttons">
          <van-button
            size="small"
            v-for="template in templates"
            :key="template.name"
            @click="useTemplate(template.data)"
          >
            {{ template.name }}
          </van-button>
        </div>
      </div>

      <div v-if="analysis" class="result-section">
        <h4>🎯 健康分析结果</h4>
        <div class="analysis-content">{{ analysis }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { showToast } from 'vant'
import aiService from '@/services/aiService'

const healthData = ref('')
const analysisType = ref('comprehensive')
const analysis = ref('')
const isLoading = ref(false)

const templates = ref([
  {
    name: '运动数据',
    data: '今天走了6000步，跑步30分钟，做了20个俯卧撑'
  },
  {
    name: '饮食记录',
    data: '早餐：牛奶面包，午餐：米饭青菜肉，晚餐：粥和小菜'
  },
  {
    name: '睡眠情况',
    data: '昨晚11点睡觉，今早7点起床，中午午休30分钟'
  },
  {
    name: '身体状况',
    data: '身高170cm，体重65kg，血压正常，最近有点疲劳'
  }
])

const analyzeHealth = async () => {
  if (!healthData.value.trim()) return

  isLoading.value = true
  analysis.value = ''

  let accumulatedText = ''

  try {
    console.log('🚀 开始流式健康分析:', healthData.value, analysisType.value)

    // 使用流式输出
    await aiService.healthManagementStream(
      12345,
      healthData.value,
      analysisType.value,
      // onMessage回调
      (content: string) => {
        console.log('📝 收到健康分析内容:', content)
        accumulatedText += content
        analysis.value = accumulatedText
      },
      // onComplete回调
      () => {
        console.log('✅ 流式健康分析完成')
        isLoading.value = false
      },
      // onError回调
      async (error: any) => {
        console.error('❌ 流式健康分析失败，尝试非流式分析:', error)

        // 流式输出失败，尝试非流式输出
        try {
          const response = await aiService.healthManagement(12345, healthData.value, analysisType.value)
          if (response.code === 200) {
            analysis.value = response.data || '健康分析完成！'
          } else {
            analysis.value = '抱歉，健康分析暂时不可用。建议保持规律作息，均衡饮食，适量运动。'
            showToast('分析失败')
          }
        } catch (fallbackError) {
          console.error('非流式输出也失败:', fallbackError)
          analysis.value = '抱歉，健康分析暂时不可用。建议保持规律作息，均衡饮食，适量运动。'
          showToast('分析失败')
        }

        isLoading.value = false
      }
    )

  } catch (error) {
    console.error('健康管理失败:', error)

    // 备选方案：直接调用非流式API
    try {
      const response = await aiService.healthManagement(12345, healthData.value, analysisType.value)
      if (response.code === 200) {
        analysis.value = response.data || '健康分析完成！'
      } else {
        analysis.value = '抱歉，健康分析暂时不可用。建议保持规律作息，均衡饮食，适量运动。'
        showToast('分析失败')
      }
    } catch (fallbackError) {
      console.error('备选方案失败:', fallbackError)
      analysis.value = '抱歉，健康分析暂时不可用。建议保持规律作息，均衡饮食，适量运动。'
      showToast('分析失败')
    }

    isLoading.value = false
  }
}

const useTemplate = (template: string) => {
  healthData.value = template
}
</script>

<style scoped>
.health-management-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.custom-nav-bar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.feature-intro {
  margin: 16px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  backdrop-filter: blur(10px);
}

.intro-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.intro-icon {
  font-size: 40px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(168, 237, 234, 0.3);
  border-radius: 16px;
}

.intro-text h3 {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.intro-text p {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.health-container {
  padding: 16px;
}

.input-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 16px;
}

.input-section h4 {
  margin: 0 0 16px 0;
  color: #2c3e50;
}

.analysis-type {
  margin: 16px 0;
}

.quick-input {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 16px;
}

.quick-input h4 {
  margin: 0 0 12px 0;
  color: #2c3e50;
}

.quick-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.result-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
}

.result-section h4 {
  margin: 0 0 16px 0;
  color: #2c3e50;
}

.analysis-content {
  font-size: 14px;
  line-height: 1.6;
  color: #2c3e50;
  background: #f8f9fa;
  padding: 16px;
  border-radius: 12px;
}
</style>
